<template>
  <div class="page-container" v-loading="loading">
    <el-form ref="form" :model="form" :label-width="$globalCss.formLabelWidth_default" class="flex_col flex_cell">

      <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>
      <!-- <div class="flex_row_wrap">
        <el-form-item label="盘点单号" prop="code" class="form_item_small">
          <span class="bold ">{{ form.code }}</span>
        </el-form-item>
        <el-form-item label="盘点类型" prop="type" class="form_item_small">
          <span class="bold ">{{ $enumShow(form.type, "CountOrderTypeEnum") }}</span>
        </el-form-item>
      </div> -->
      <ex_super_desc v-bind="baseOption" :data="form" :attrs="$defaultDetailDescAttrs" />
      <ex_header_spiler :title="$t('label_task_detail')">
        <template v-slot:left>
          <el-button @click="addLine" type="primary">{{ $t('label_stocktaking_profit') }}</el-button>
        </template>
        <el-button @click="completeResult" type="primary">{{ $t('label_inventory_confirm') }}</el-button>
      </ex_header_spiler>


      <ex_super_table ref="table" v-bind="tableOption" :autoFlex="true" :autoPage="true"
        url="/wms-api/inside/CountOrderRpc/selectDetailPage.json" :urlParams="{ orderId: form.id }"
        @grid-data-change="dataChange">

      </ex_super_table>
      <!-- <el-form-item label-width="0">
        <span>
          <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
        </span>
      </el-form-item> -->
    </el-form>

    <ex_super_dialog_form ref="formDialog" v-bind="dialog" :title="$tt(['label_stocktaking_profit', 'label_add_record'])"
      @afterSubmitSuccess="addRecord">

    </ex_super_dialog_form>
  </div>
</template>



<script>
import router_params from '@/mixin/router_params';
const default_form = {
  type: null,
  countOrderId: null,
  code: null,
  isBlind: null,
  actuallyCountList: []
}
export default {
  title: 'label_stocktaking_operate',
  mixins: [router_params],
  components: {},
  data() {
    return {
      loading: false,
      form: _.cloneDeep(default_form),
      baseOption: {
        model: [
          { key: 'orderNo', label: 'label_stocktaking_order_code', },
          { key: 'bizType', label: 'label_business_type', },

          { key: 'status', label: 'label_status', formatter: (r, c, v, i) => this.$enumShow(v, "CountOrderStatusEnum"), },
          { key: 'type', label: 'label_stocktaking_type', formatter: (r, c, v, i) => this.$enumShow(v, "CountOrderTypeEnum"), },
          { key: 'mode', label: 'label_stocktaking_way', formatter: (r, c, v, i) => this.$enumShow(v, "CountOrderModeEnum"), },
          // { key: 'isDiff', label: 'label_is_diff', formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum"), },
          // { key: 'diffNum', label: 'label_diff_count', },
          { key: 'totalLocationNum', label: 'label_warehouse_location_count', },
          { key: 'totalSkuCategoryNum', label: 'label_sku_count_sum', },
          { key: 'creator', label: 'label_create_user', },
          { key: 'gmtCreate', label: 'label_create_time', 'min-width': 120, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$dateFormat(v) },
        ],
      },
      tableOption: {
        // defaultPageSize: 2, simplePage: true,
        model: [
          { key: 'areaCode', label: 'label_warehouse_area', 'width': 120, },
          { key: 'locationCode', label: 'label_warehouse_location', 'min-width': 130, },

          { key: 'customerCode', label: 'label_customer_info', 'width': 100, 'show-overflow-tooltip': true, },
          { key: 'subContainerCode', label: 'label_box_code', 'width': 120, if: () => this.TOB },
          {
            key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': 130,
            formatter: (r, c, v) => r.skuId < 0 ? "——" : v
          },
          {
            key: 'skuName', label: 'label_sku_name', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v) => r.skuId < 0 ? "——" : this.$formatNameCode(v, r.skuNameEn)
          },
          // { key: 'customerCode', label: 'label_customer_info', 'width': 100, 'show-overflow-tooltip': true, },

          {
            key: 'stockNum', label: 'label_stock_count', 'width': 100, 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.isBlind ? this.$tt('label_blind_check') : v
          },

          {
            key: 'countNum', label: 'label_check_count', 'min-width': 120,

            render: (h, { row, column }) => {
              let value = row[column.property]
              if (this.disabledItem(row)) {
                value = this.finishCount(row)
                if (this.TOB) {
                  return (<div class={value != undefined ? (value > 0 ? 'color_success' : 'color_danger') : 'color_info'}>
                    {value != undefined ? (value > 0 ? this.$t('label_exist') : this.$t('label_lack')) : this.$t('label_wait_operate')}
                  </div>)
                } else {
                  return (<div class={value != undefined ? (value > 0 ? 'color_success' : 'color_danger') : 'color_info'}>
                    {value}
                  </div>)
                }

              }
              const isOperate = !!row.countTime

              if (this.TOB) {
                const inner = (<div class={isOperate ? (value > 0 ? 'color_success' : 'color_danger') : 'color_info'}>
                  {isOperate ? (value > 0 ? this.$t('label_exist') : this.$t('label_lack')) : this.$t('label_wait_operate')}
                </div>)
                const hasCount = row.firstCountNum > 0 ? row.firstCountNum : row.stockNum
                return (<el-checkbox value={value > 0 ? true : false} onChange={e => this.countInput(e ? hasCount : -1, row)}>{inner}</el-checkbox>)
              }
              return (
                <el-input-number value={value} class="w_fill" min={0} max={999999} step-strictly onChange={e => this.countInput(e, row)} />
              )
            }
          },
          {
            type: 'operate', 'min-width': 140,
            renderHeader: (h, { column }) => {
              return (<div class="flex_row_wrap flex_center">
                <div>{this.$t(column.label)}</div>
                {this.canBatchSubmit ? (<el-button type="primary" class="mg_l2" onClick={this.submitItemBatch}>{this.$t('label_batch_submit')}</el-button>) : null}
              </div>)
            },
            operate: [
              { label: "label_submit", if: (row) => this.canSubmit(row), click: (row, i, list) => this.submitItem([row]) }
              // {
              //   label: 'label_remove', if: (row) => !row.id, class: 'button_text_danger', click: (row, i, list) => list.splice(i, 1)
              // }
            ]
          }
        ]
      },
      dialog: {
        customClass: 'dialog_auto',
        form: {
          itemClass: "form_item_small", inputClass: "form_input_small",
          model: [
            {
              key: 'locationCode', label: 'label_warehouse_location',
              render: (h, { data, item }) => {
                const value = data[item.key]
                const isSkuType = this.form.type == 'SKU'
                return (
                  <base_location_select value={value} class="form_input_small" checkArea={false}
                    option={{ label: 'labelStr', value: 'code' }}
                    onInput={e => this.$set(data, item.key, e)}
                  />
                )
                if (isSkuType) {
                  return (
                    <base_location_select value={value} class="form_input_small" checkArea={false}
                      option={{ label: 'labelStr', value: 'code' }}
                      onInput={e => this.$set(data, item.key, e)}
                    />
                  )
                } else {
                  return (
                    <ex_select_auto value={value} class="form_input_small" type="select" items={this.locationCodeList}
                      onInput={e => this.$set(data, item.key, e)}
                    />
                  )
                }
              }
            },
            {
              key: "type", label: "label_stocktaking_profit_type", type: 'ex_radio_group_auto', i18n: true, disabled: true, items: [
                { label: 'label_sku', value: 'SKU' }, { label: 'label_box_code', value: 'BOX' },
              ]
            },
            {
              key: 'skuOnlyCode', label: 'label_select_sku', if: (data) => data.type == 'SKU',
              render: (h, { data, item }) => {
                const value = data[item.key]
                const isSkuType = this.form.type == 'SKU'
                const buildSkuOption = it => ({ label: this.$formatNameCode(it.skuName, it.skuBarcode), value: it['skuOnlyCode'] })
                return (
                  <sku_selec_input value={value} class="form_input_small"
                    option={buildSkuOption}
                    onInput={e => {
                      this.$set(data, item.key, e)
                    }}
                  />
                )

              },
            },
            {
              key: 'subContainerCode', label: 'label_box_code', if: (data) => data.type == 'BOX',
            },
            {
              key: 'countNum', label: 'label_check_count', if: (data) => !this.TOB,
              render: (h, { data, item }) => {
                const value = data[item.key]
                return (<el-input-number class="form_input_small" value={value} onInput={e => this.$set(data, item.key, e)} step-strictly min={1} max={999999} />)
              }
            }
          ],
          rules: {
            'locationCode': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'type': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

            'skuOnlyCode': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            subContainerCode: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            countNum: { required: true, type: 'number', message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          },
        }
      },
      tempSubmitList: [

      ],
    }

  },

  computed: {
    canBatchSubmit() {
      return this.$refs.table.getData().some(it => this.canSubmit(it))
    },
    TOB() {
      return this.form.bizType == 'TOB'
    },
    isBlind() {
      return this.form.isBlind === 'Y'
    },
    locationCodeList() {
      return _.uniqBy(this.form.actuallyCountList.map(it => ({ label: it.locationCode, value: it.locationCode })), 'value')
    },
    skuOnlyCodeList() {
      return _.uniqBy(this.form.actuallyCountList.map(it => ({ label: this.$formatNameCode(it.skuName, it.skuBarcode), value: it.skuOnlyCode })), 'value')
    },
  },
  methods: {
    finishCount(it) {
      return it.secondCountNum != undefined ? it.secondCountNum : it.firstCountNum
    },
    disabledItem(it) {
      return it.status == 'COMPLETE' || it.isEmptyLocationTask == 'Y'
    },
    canSubmit(it) {
      return !!it.countTime && !this.disabledItem(it)
    },
    dataChange(list) {
      list.filter(it => !this.disabledItem(it)).forEach(row => {
        const temp = _.find(this.tempSubmitList, t => t.id == row.id)
        if (temp) {
          this.$set(row, 'countTime', temp.countTime)
          this.$set(row, 'countNum', temp.countNum)
        }
      })
    },
    countInput(e, row) {
      this.$set(row, 'countTime', new Date().getTime())
      this.$set(row, 'countNum', e)
      const temp = _.find(this.tempSubmitList, t => t.id == row.id)
      if (temp) {
        temp.countTime = row.countTime
        temp.countNum = row.countNum
      } else {
        this.tempSubmitList.push(row)
      }
    },
    init_data_default(params) {

      this.loading = true
      this.$ajax({
        url: "/wms-api/inside/CountOrderRpc/detail.json",
        method: 'post',
        data: { id: params.id },
        success: (res) => {
          if (res && res.data) {
            this.form = Object.assign({}, _.cloneDeep(default_form), res.data)
            // this.getRemoteData(params.id)
            this.$nextTick(() => {
              this.$refs.table.loadData({})
            })
          }
          this.fixTabLabel()
        },
        complete: () => {
          this.loading = false
        }
      })
      this.fixTabLabel()
    },
    fixTabLabel() {
      if (!!this.form.orderNo) {
        this.$emit("tagModifyLabel", {
          _key: 'label_name_code', name: this.$tt("label_stocktaking_operate"),
          code: this.form.orderNo || ''
        })
      } else {
        this.$emit("tagModifyLabel", "label_stocktaking_operate")
      }
    },
    getRemoteData(id) {
      this.$ajax({
        url: "/wms-api/inside/CountOrderRpc/selectWaitDoDetail.json",
        method: 'post',
        data: { orderId: id },
        success: (res) => {
          // let time = new Date().getTime()
          // res.data.rows.forEach(it => {
          //   it.countNum = 0
          //   // it.countTime = time
          // })
          this.form.actuallyCountList = res.data.rows
          // this.locationCodeList =
          //   _.uniq(res.data.rows.map(it => {
          //     return it.locationCode
          //   }))
          // this.skuOnlyCodeList =
          //   _.uniq(res.data.rows.map(it => {
          //     return it.skuOnlyCode
          //   }))
        }
      })
    },
    addLine() {
      // let locationCode = _.find(this.dialog.form.model, it => it.key == "locationCode")
      // locationCode.items = this.locationCodeList
      this.$refs.formDialog.showNew({
        data: {
          type: this.TOB ? 'BOX' : 'SKU',
          countNum: 1,
        },
        onlySetData: true,
      })
    },
    addRecord(data) {
      data.countOrderId = this.form.id
      data.bizType = this.form.bizType
      if (data.type == 'SKU') {
        data.subContainerCode = null
      } else if (data.type == 'BOX') {
        data.skuOnlyCode = null
      }
      this.$ajax({
        url: "/wms-api/inside/CountOrderRpc/moreDetailValidInCount.json",
        type: 'json',
        method: 'post',
        data,
        success: (res) => {
          if (res && res.data) {
            const submitItemObj = {
              countOrderId: this.form.id,
              bizType: this.form.bizType,
              areaCode: res.data.areaCode,//	string 	库区编码
              locationCode: res.data.locationCode,//		string 	库位编码
              customerId: res.data.customerId,//		string 	客户编码
              customerName: res.data.customerName,//		string 	客户编码
              customerCode: res.data.customerCode,//		string 	客户编码
              skuId: res.data.skuId,
              skuBarcode: res.data.skuBarcode,//	string 	商品条形码

              skuOnlyCode: res.data.skuOnlyCode,//	string 	商品条形码
              skuName: res.data.skuName,//	string 	商品名称
              skuNameEn: res.data.skuNameEn,//	string 	商品名称
              stockNum: 0,// integer   库存数量
              countNum: data.countNum,//integer 	盘点数量
              countTime: new Date().getTime(),
            }
            if (data.type == 'BOX') {
              submitItemObj.subContainerCode = res.data.subContainerCode
              submitItemObj.countNum = res.data.stockNum
            }
            this.submitItem([submitItemObj])

          }

        },

      })
    },
    pageChangeBefore(call) {
      if (this.canBatchSubmit) {
        this.$confirm(this.$t('tip_has_change_stocktaking_data_confirm'), this.$t("label_tip"), {
          type: 'warning'
        }).then(() => {
          call()
        }).catch(() => {

        });
      } else {
        call()
      }
    },
    submitItemBatch() {
      this.submitItem(this.$refs.table.getData().filter(it => this.canSubmit(it)))
    },
    submitItem(list) {
      this.$ajax({
        url: "/wms-api/inside/CountOrderRpc/commit.json",
        type: 'json',
        method: 'post',
        data: {
          countOrderId: this.form.id,
          taskNo: this.form.taskNo,
          actuallyCountList: list.map(it => {
            it.countOrderDetailId = it.id
            if (this.TOB) {
              // if (it.countNum) {
              //   it.countNum = it.stockNum
              // } else {
              //   it.countNum = -1
              // }
            }
            return it
          })
        },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.return_emit(null, "reload")
          this.init_data_default({ id: this.form.id })
          // this.$message.success(this.$tt('tip_submit_success'))
          // this.return_emit(null, "reload")
          // this.refresh_data()
          // this.$tag.tagClose(null, this.intoPath)
        },
      })
    },
    completeResult() {
      this.$confirm(this.$tt('label_inventory_confirm'), this.$tt('label_tip'), {
        confirmButtonText: this.$tt('label_confirm'),
        cancelButtonText: this.$tt('label_cancel'),
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/wms-api/inside/CountOrderRpc/finishCountTask.json",
          method: 'post',
          data: { orderId: this.form.id },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.return_emit(null, "reload")
            this.return_page_back()
          },
        })
      }).catch(() => {

      });


    }

  }

}
</script>

<style scoped></style>
